﻿window.SilverQuery = { eventRegistry: {}, contentKey: "", object: null };

SilverQuery.createEventCallback = function(callbackId) {
    var fn = function(e) {
        SilverQuery.eventRegistry[callbackId] = e;
        var host = document.getElementById("SilverQueryObject");
        return host.content[SilverQuery.contentKey].TriggerEventCallback(callbackId);
    };

    return fn;
}

SilverQuery.createEmptyMap = function() {
    return {};
}

SilverQuery.createCallback = function(callbackId) {
    var fn = function() {
        var host = document.getElementById("SilverQueryObject");
        host.content[SilverQuery.contentKey].TriggerCallback(callbackId);
    };

    return fn;
}

// Function called by the Silverlight component when it has loaded.
SilverQuery.registerComponent = function(contentKey) {
    SilverQuery.contentKey = contentKey;
    $(document).ready(function() {
        document.getElementById("SilverQueryObject").content[contentKey].ready();
    });
}

SilverQuery.createObject = function(xapPath, params, noSilverlightCallback) {
    if (document.getElementById("SilverQueryObject") != null)
        throw new Error("There can be only one SilverQueryObject on the page.");

    var properties = { width: "0", height: "0", version: "3.0.40624.0" };
    if (!Silverlight.isInstalled(properties.version) && noSilverlightCallback) {
        noSilverlightCallback();
        return;
    }

    // Force reloading the .xap file from scratch if running on localhost.
    if (document.location.host.indexOf("localhost") != -1) {
        xapPath += (xapPath.indexOf('?') == -1) ? "?" : "&";
        xapPath += "nocache=" + new Date().getMilliseconds();
    }

    document.write(Silverlight.createObject(
        xapPath,  // source
        null,  // parent element
        "SilverQueryObject",  // id for generated object element
        {}, // no events specified
        properties,
        (params != null) ? $.param(params).replace("&", ",") : null
    ));
}